package com.example.getfromservice.Book;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import com.example.getfromservice.DB.MySQLiteHelper;

public class BookDAO {
	
	  private SQLiteDatabase database = null;
	  private MySQLiteHelper dbHelper;
	  private Cursor cursor;
	  private String[] allColumns = {MySQLiteHelper.BOOK_COLUMN_ID, MySQLiteHelper.BOOK_COLUMN_BOOK_ID, MySQLiteHelper.BOOK_COLUMN_AUTHOR , MySQLiteHelper.BOOK_COLUMN_CHANGES, MySQLiteHelper.BOOK_COLUMN_ISBN, MySQLiteHelper.BOOK_COLUMN_TITLE, MySQLiteHelper.BOOK_COLUMN_CAT_ID };
	  
	  
	 public BookDAO( Context context ) {
		  
		    dbHelper = new MySQLiteHelper(context);
		    
		  }

	 public void open() throws SQLException {
			  
		    database = dbHelper.getWritableDatabase();
		    
		    Log.i("DAOBOOK","OPEN()");
		    
		  }

	 
	 public void close() {
			  
		    dbHelper.close();
		    
		    Log.i("DAOBOOK","CLOSE()");
		    
		  }
	 
	 public Bitmap getImage(String name)
		{
			
			String path = Environment.getExternalStorageDirectory().toString();
	
			InputStream fileIn = null;
			
			File file = new File(path, name + ".jpg");
			if (file.exists())
			{
				try
				{
					fileIn = new FileInputStream(file);
					Bitmap bmp = BitmapFactory.decodeStream(fileIn);

					fileIn.close();
					return bmp;
				} catch (Exception e)
				{
					return null;
				}
			}
			
			return null;
		}
		
		
	 public Book selectBookfromDB( int book_id  )
	 	{
			 Log.i("SELECT FROM BOOK WHERE ", "ID = "+book_id);
			 
			 
			 cursor = database.query( MySQLiteHelper.TABLE_BOOK, allColumns, MySQLiteHelper.BOOK_COLUMN_BOOK_ID +"=" +book_id, null, null, null, null);
				
			 
				if ( cursor != null)
					{
					
			        	cursor.moveToFirst();
					}
			
				Book book = new Book();
			    if(doesBookexist(cursor.getInt(1)))
			    	{
			    		book = cursorToBook(cursor);
			    	}	
		    
			

			return book; 
		
		}
		  
	 
	 public List<Book> getAllBooks(String idCategory)
		{
			
			List<Book> list = new ArrayList<Book>();

			cursor = database.query(MySQLiteHelper.TABLE_BOOK, allColumns, MySQLiteHelper.BOOK_COLUMN_CAT_ID + "=?" ,new String[] { String.valueOf( idCategory ) }, null, null, null, null);
		
			cursor.moveToFirst();
			Log.i("LISTBOOK",cursor.getCount()+"");
			
			while (!cursor.isAfterLast())
			{
				
				Book c = new Book();
				
				c.setIdDB(cursor.getInt(0));
				c.setID(cursor.getInt(1));
				c.setAuthor(cursor.getString(2));
				c.setChanges(cursor.getInt(3));
				c.setISBN(cursor.getString(4));
				c.setName(cursor.getString(5));
				c.setCategory_id(cursor.getString(6));
				
				
				Bitmap img = getImage(c.getID()+"");
				c.setImage(img);
				
				if( c.getChanges() != 3)
					{
						list.add(c);
					}

				cursor.moveToNext();
			}
			cursor.close();
			
			return list;
		}
	 
	 public void addBooks(List<Book> cs,int cat_id)
		{
		
		
			try{

			for (Book c : cs)
			{

				ContentValues values = new ContentValues();
				
				values.put(MySQLiteHelper.BOOK_COLUMN_CAT_ID, cat_id);
				
				values.put(MySQLiteHelper.BOOK_COLUMN_BOOK_ID, c.getID());
				
				values.put(MySQLiteHelper.BOOK_COLUMN_ISBN, c.getISBN());
				
				values.put(MySQLiteHelper.BOOK_COLUMN_TITLE, c.getTitle());
				
				values.put(MySQLiteHelper.BOOK_COLUMN_AUTHOR, c.getAuthor());
				
				values.put(MySQLiteHelper.BOOK_COLUMN_CHANGES, "0");

				database.insert(MySQLiteHelper.TABLE_BOOK, null, values);
				
				
				
			}
			}catch(Exception e ){
				Log.e("BookDAO", "E "+e.getMessage());
			}
			
		}
	 
	 
	 public void addBook(String cat_id, Book c)
		{
			
			
			ContentValues values = new ContentValues();
			
			values.put(MySQLiteHelper.BOOK_COLUMN_CAT_ID, cat_id);
			
			values.put(MySQLiteHelper.BOOK_COLUMN_BOOK_ID, c.getID());
			
			values.put(MySQLiteHelper.BOOK_COLUMN_ISBN, c.getISBN());
			
			values.put(MySQLiteHelper.BOOK_COLUMN_TITLE, c.getTitle());
			
			values.put(MySQLiteHelper.BOOK_COLUMN_AUTHOR, c.getAuthor());
			
			values.put(MySQLiteHelper.BOOK_COLUMN_CHANGES, "2");

			database.insert(MySQLiteHelper.TABLE_BOOK, null, values);
	
		}
		
	 
	 public void deleteBook( Book book ) {
			   
			    
			    database.delete(MySQLiteHelper.TABLE_BOOK, MySQLiteHelper.BOOK_COLUMN_BOOK_ID + " = " + book.getID(), null);
			    
		  }
		  
	
	 public int deleteAllBooks(){
				
				int number_del_row = database.delete(MySQLiteHelper.TABLE_BOOK,null,null);
				
				return number_del_row;
		 }
		  
		  
	 private Book cursorToBook(Cursor cursor) {
				 
				
				Book c = new Book();
				
				c.setIdDB(cursor.getInt(0));
				c.setID(cursor.getInt(1));
				c.setAuthor(cursor.getString(2));
				c.setChanges(cursor.getInt(3));
				c.setISBN(cursor.getString(4));
				c.setName(cursor.getString(5));
				c.setCategory_id(cursor.getString(6));

	
				Bitmap img = getImage(c.getID()+"");
				if( img == null)
				{
					Log.i("BOOKDAOIMG","NULL");
					}
				
				c.setImage(img);
				
				return c;
			  }	  

			 
	 public boolean doesBookexist( int book_id )
			  {
			
				cursor = database.query(MySQLiteHelper.TABLE_BOOK, allColumns, MySQLiteHelper.BOOK_COLUMN_BOOK_ID +"="+book_id, null, null, null, null);
				cursor.moveToFirst();
				if(cursor.getCount() == 0 ||  cursor.getInt(3) == 3 ) 
				 	{ 
					    cursor.close();
						return false;
				    }
				 else 
				 	{
					    
					 	return true;
				 	}
				 
			 

			  }
			
	 public void updateBookinDB( Book book ){
					
					ContentValues values = new ContentValues();
				
					values.put(MySQLiteHelper.BOOK_COLUMN_CAT_ID, book.getCategory_id());
					
					values.put(MySQLiteHelper.BOOK_COLUMN_BOOK_ID, book.getID());
					
					values.put(MySQLiteHelper.BOOK_COLUMN_ISBN, book.getISBN());
					
					values.put(MySQLiteHelper.BOOK_COLUMN_TITLE, book.getTitle());
					
					values.put(MySQLiteHelper.BOOK_COLUMN_AUTHOR, book.getAuthor());
					
					values.put(MySQLiteHelper.BOOK_COLUMN_CHANGES, book.getChanges());
				 			
				    // Updating 
				   int number_row = database.update(MySQLiteHelper.TABLE_BOOK, values,  MySQLiteHelper.BOOK_COLUMN_BOOK_ID +"=?" , new String[] { String.valueOf(book.getID()) });
				   
				   Log.i("UPDATE","Row = " +number_row);
				}
			  
				
	public int getLastInsertId() {
					
					Cursor cursor = database.query(MySQLiteHelper.TABLE_BOOK, allColumns,null, null, null, null, null);
					cursor.moveToLast();
					
					int last_id = (int)cursor.getLong(1);
					
					return last_id;
				}
				
				
	public  List<Book> getAllBooksSync()
		{
				List<Book> list_b = new ArrayList<Book>();
				Book b;   
				//Changes in DB 0 - nothing ; 1 - update; 2 - new ;  3- delete
				cursor = database.query(MySQLiteHelper.TABLE_BOOK, allColumns,null, null, null, null, null);
						
				cursor.moveToFirst();
					    
				while( !cursor.isAfterLast() ) {
					    	
					b = cursorToBook(cursor);
					list_b.add(b);
					cursor.moveToNext();
					      
					}
				// Make sure to close the cursor
				cursor.close();
					
				
					    
			return list_b;
		}
}
